<?php

namespace W3;

/**
 * cookie支持
 *
 * @author edikud
 * @date 2022/10/22
 * @copyright Copyright (c) 2022 W3 (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Cookie
{
	
    /**
     * cookie数组
     *
     * @var array
     */
    protected static $bag = [];
	
    protected static $config = [
        'prefix' => '',
        'path' => '/',
        'domain' => '',
        'secure' => false,
        'httponly' => false
    ];
	
    /**
     * 获取cookie保存数据
     * @access public
     * @return array
     */
    public static function export(): array
    {
        return self::$bag;
    }
	
    /**
     * 获取和设置配置参数
     * @param string $method  参数名
     * @param mixed $arguments 参数值
     * @return mixed
     */
    public static function __callStatic($method, $arguments)
    {
        if(isset(self::$config[$method])){

			$argument = (!empty($arguments)) ? $arguments[0] : NULL;
			
			if(is_null($argument)) {
				
				return self::$config[$method];
			}
			
			self::$config[$method] = $argument;
		}
    }

    /**
     * 获取指定的COOKIE值
     *
     * @param string $key 指定的参数
     * @param string|null $default 默认的参数
     * @return mixed
     */
    public static function get(string $key, ?string $default = null)
    {
        $key = self::$config['prefix'] . $key;
        $value = $_COOKIE[$key] ?? $default;
        return is_array($value) ? $default : $value;
    }

    /**
     * 设置指定的COOKIE值
     *
     * @param string $key 指定的参数
     * @param mixed $value 设置的值
     * @param integer $expire 过期时间,默认为0,表示随会话时间结束
     */
    public static function set(string $key, $value, int $expire = 0)
    {
        $key = self::$config['prefix'] . $key;
        $_COOKIE[$key] = $value;
        self::$bag[$key] = [$key, $value, $expire, self::$config['path'], self::$config['domain'], self::$config['secure'], self::$config['httponly']];
    }

    /**
     * 删除指定的COOKIE值
     *
     * @param string $key 指定的参数
     */
    public static function delete(string $key)
    {
        $key = self::$config['prefix'] . $key;
        if (!isset($_COOKIE[$key])) {
            return;
        }

        self::$bag[$key] = [$key, '', -1, self::$config['path'], self::$config['domain'], self::$config['secure'], self::$config['httponly']];
        unset($_COOKIE[$key]);
    }

    /**
     * 是否存在Cookie参数
     * @access public
     * @param  string $name 变量名
     * @return bool
     */
    public static function has(string $name): bool
    {
        $name = self::$config['prefix'] . $name;
        return isset($_COOKIE[$name]);
    }
}

